package com.bootredis.bootredis.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bootredis.bootredis.mapper.EmpBeanMapper;
import com.bootredis.bootredis.service.EmpService;
import com.bootredis.bootredis.vo.Emp;


import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;

import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
public class Contro {
    @Autowired
    @Qualifier("serviceimpl")
    EmpService empService;

    @Autowired
    EmpBeanMapper empBeanMapper;
    @Autowired
    RestHighLevelClient elasticsearchClient;

    // mybatis - plus   查询
    @RequestMapping("/qpxmq")
    @ResponseBody
    public List<Emp> qpxmq(){
        QueryWrapper<Emp> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("empno","ename","job","mgr","hiredate","sal","comm","deptno","wsid" );
        List<Emp> emps = empBeanMapper.selectList(queryWrapper);
        emps.forEach(System.out::println);
        return   emps;
    }
    // mybatis - plus   插入
    @RequestMapping("/instt")
    @ResponseBody
    public int  instt(){
//        QueryWrapper<Emp> queryWrapper = new QueryWrapper<>();
//        queryWrapper.
        Emp  aa = new Emp();
        aa.setEname("wc");
        int emps = empBeanMapper.insert(aa);
        return   emps;
    }
    //jieshu //
    @RequestMapping("/aa")
    @ResponseBody
    public   List<Emp> aa(){
        List<Emp> all = empService.findAll();
        return all;
    }
    /*
        *操作索引
        创建索引
     */
    @RequestMapping("/bb")
    @ResponseBody
    public  CreateIndexResponse bb() throws IOException {
//        1、创建索引请求
        CreateIndexRequest createIndexRequest = new CreateIndexRequest("wcnbqq");
//        2、客户端执行请求 createIndexRequest,请求后获得响应
        CreateIndexResponse createIndexResponse = elasticsearchClient.indices().create(createIndexRequest, RequestOptions.DEFAULT);
//        System.out.println(createIndexResponse);
        return createIndexResponse;
    }
    /*
         *操作索引
        获取索引,判断是否存在
     */
    @RequestMapping("/cc")
    @ResponseBody
    public  boolean cc() throws IOException {
//        1、获取索引请求
        GetIndexRequest getIndexRequest = new GetIndexRequest("wcnb");
        //判断索引是否存在  exists (true|false)
        boolean exists = elasticsearchClient.indices().exists(getIndexRequest,RequestOptions.DEFAULT);
        return exists;
    }

    /*
         *操作索引
       删除索引
    */
    @RequestMapping("/dd")
    @ResponseBody
    public  boolean dd() throws IOException {
//       删除
        DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest("wcnb");
        //
        AcknowledgedResponse delete = elasticsearchClient.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
        return delete.isAcknowledged();
    }

    /*
     *操作文档   PUT   /wcnbqq/fc/1
     * 添加内容（文档）
     */
    @RequestMapping("/ee")
    @ResponseBody
    public  String ee() throws IOException {
        Emp emp = new Emp();
        emp.setEname("wc");
//        emp.setComm(12.55);
        //连接索引 -> 创建请求
        IndexRequest indexRequest = new IndexRequest("wcnbqq"); //索引
        indexRequest.type("fc");//mapping
        indexRequest.id("1"); //id
//        indexRequest.timeout("5000s");//1s   超时设置
//        indexRequest.versionType(VersionType.EXTERNAL);//文档类型
//        indexRequest.version(1); //文档版本
//        indexRequest.setRefreshPolicy("wait_for");//以字符串形式刷新策略
//        将数据放入请求
        String json = JSON.toJSONString(emp);
        indexRequest.source(json,XContentType.JSON);
        //客户端发送请求 ,获取响应结果
        IndexResponse index = elasticsearchClient.index(indexRequest, RequestOptions.DEFAULT);
        System.out.println(index.status());  //状态
        return index.toString();//结果
    }
    /*
     判断文档是否存在  GET  /wcnbqq/fc/1
     */
    @RequestMapping("/ff")
    @ResponseBody
    public  Boolean ff() throws IOException{
        GetRequest getRequest = new GetRequest("wcnbqq","fc","1");
//        getRequest.fetchSourceContext(new FetchSourceContext(false));
//        getRequest.storedFields("_none_");
        boolean exists = elasticsearchClient.exists(getRequest, RequestOptions.DEFAULT);//判断
        return exists;
    }
    /*
        获取文档信息
     */
    @RequestMapping("/gg")
    @ResponseBody
    public String gg() throws IOException {
        GetRequest getRequest = new GetRequest("wcnbqq","fc","1");
        GetResponse exists = elasticsearchClient.get(getRequest, RequestOptions.DEFAULT);//判断
        String sourceAsString = exists.getSourceAsString();//获取文档的内容
        return sourceAsString;
    }
    /*
        更新文档信息
     */
    @RequestMapping("/hh")
    @ResponseBody
    public String   hh() throws IOException {
        UpdateRequest updateRequest = new UpdateRequest("wcnbqq","fc","1");
        updateRequest.timeout("1s");
        Emp emp = new Emp();
        emp.setEname("wcnb");
        updateRequest.doc(JSON.toJSONString(emp),XContentType.JSON);
        UpdateResponse update = elasticsearchClient.update(updateRequest, RequestOptions.DEFAULT);

        System.out.println(update.status());
        return update.toString();
    }
    /*
        删除文档信息
     */
    @RequestMapping("/ii")
    @ResponseBody
    public String   ii() throws IOException {
        DeleteRequest updateRequest = new DeleteRequest("wcnbqq","fc","1");
        updateRequest.timeout("1s");
        Emp emp = new Emp();
        emp.setEname("wcnb");
        DeleteResponse update = elasticsearchClient.delete(updateRequest, RequestOptions.DEFAULT);

        System.out.println(update.status());
        return update.toString();
    }
    /*
     批量穿入文档信息
  */
    @RequestMapping("/jj")
    @ResponseBody
    public String   jj() throws IOException {
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout("1s");
        ArrayList<Emp> emps = new ArrayList<>();
        Emp a1 = new Emp();
        a1.setEname("qpzm1111");
        Emp a2 = new Emp();
        a2.setEname("qpzm2222");
        Emp a3 = new Emp();
        a3.setEname("qpzm3333");
        emps.add(a1);
        emps.add(a2);
        emps.add(a3);
        //批处理
        for (int i = 0;i<emps.size();i++)
        {
            bulkRequest.add(new IndexRequest("wcnbqq","fy","1")
                .id(""+(1+i))
                    .source(JSON.toJSONString(emps.get(i)),XContentType.JSON)
            ); //索引)
        }
        BulkResponse bulk = elasticsearchClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        System.out.println(bulk.hasFailures());//是否失败,返回false代表成功
        return "";
    }
    /*
    搜索
 */
    @RequestMapping("/kk")
    @ResponseBody
    public String   kk() throws IOException {
        SearchRequest searchRequest = new SearchRequest("wcnbqq");
        //构建搜索条件
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //查询条件   使用termQueryBuilder 来实现
        // QueryBuilders.termQuery  精确匹配
        // QueryBuilders.matchAllQuery()//查询匹配所有
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("ename", "wc");
        searchSourceBuilder.query(termQueryBuilder);
//        searchSourceBuilder.from(); //分页  开始
//        searchSourceBuilder.size();//分页  结束
        searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS)); //超时时间
        searchRequest.source(searchSourceBuilder); //放入请求
        SearchResponse search = elasticsearchClient.search(searchRequest, RequestOptions.DEFAULT);//执行
        for (SearchHit aa :search.getHits().getHits())
        {
            System.out.println(aa.getSourceAsMap());
        }

        return JSON.toJSONString(search.getHits());
    }
}